<?php

include_once('../dao/imageDAO.php');
include_once('SimpleImage.php');

function addImage($proID, $fileName) {
    return insertImage($proID, $fileName);
}

function getImagesByID($imageID) {
    return loadImagesByID($imageID);
}

function editImage($imgID, $fileName) {
    return updateImage($imgID, $fileName);
}

function getImagesByProID($proID) {
    return loadImagesByProductID($proID);
}

function findExts($filename) {
    $filename = strtolower($filename);
    $exts = split("[/\\.]", $filename);
    $n = count($exts) - 1;
    $exts = $exts[$n];
    return '.' . $exts;
}

function deletePhysicalImage($filePath) {
    if (file_exists($filePath)) {
        unlink($filePath);
    }
}

function uploadImage($image, $suffix, $oldID, $proID) {
    $imagePath = "../img/product/";
    $newName = $proID . "-" . $suffix . findExts($image['name']);
//    if (!is_dir($imagePath))
//        mkdir($imagePath);

    if (!isset($image['name']) || $image['name'] == '') {
        return '';
    } else {
        if ($oldID == '') {
            addImage($proID, $newName);
        } else {
            $imgRow = getImagesByID($oldID);
            deletePhysicalImage($imagePath . $imgRow['IMG_PATH']);
            editImage($oldID, $newName);
        }

        if ((($img1["type"] == "image/gif")
                || ($image["type"] == "image/jpg")
                || ($image["type"] == "image/jpeg")
                || ($image["type"] == "image/pjpeg")
                || ($image["type"] == "image/png"))) {
            move_uploaded_file($image["tmp_name"], $imagePath . $newName);
        } else {
            return '';
        }
    }
    return $newName;
}

function reSize($newName, $proID) {
    if ($newName != '') {
        $path_thumbs = "../img/product/thumbnail/";
        $path_source = "../img/product/" . $newName;
//        if (!is_dir($path_thumbs))
//            mkdir($path_thumbs);
        $image = new SimpleImage();
        $image->load($path_source);
        $image->resize(178, 222);
        $image->save($path_thumbs . $newName);
    }
}

function getMainImageByProID($proID) {
    return mysql_fetch_array(getImagesByProID($proID));
}

?>